﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using DCS.Business.Interface;
using System.Configuration;
using MessageSyncTest.ESB;
using System.Linq;
using DCS.Business.Model;

namespace MessageSyncTest
{
	public partial class Form1 : Form
	{
		public static IMessageSyncer BusinessObject;
		static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		static bool esbHeaderBit = false;

		public Form1()
		{
			InitializeComponent();

			IUnityContainer myContainer = new UnityContainer();
			UnityConfigurationSection section
			  = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
			section.Containers["Business"].Configure(myContainer);

			BusinessObject = myContainer.Resolve<IMessageSyncer>();
			BusinessObject.Init();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			BusinessObject.DetectAndSync();
		}

		private void button2_Click(object sender, EventArgs e)
		{
			Logger.Info("程序初始化");

		}


		private void CallESBWSOnce()
		{


			//ESBTMPPPFSService1 esbparam = GetESBParam(group, pfsList, false);

			//ESBHeadInfo esbheader = GetESBHeader(ECIFSyncStatus.Success);
			//Logger.WarnFormat("{2}-{0}-{1}", "TestGroupName", esbheader.ServiceSn, 256);
			//CallESBWS(esbparam, esbheader);


		}

		private void CallESBWS(ESBTMPPPFSService1 esbparam, ESBHeadInfo esbheader)
		{
			ESBTMPPPFSService service = new ESBTMPPPFSService();
			service.RequestEncoding = Encoding.UTF8;
			service.SoapVersion = System.Web.Services.Protocols.SoapProtocolVersion.Soap11;
			service.ESBHeader = esbheader;

			/////////////////////////
			//System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(ESBTMPPPFSService1), "http://www.ceair.com/ESB/");

			//FileStream fs = new FileStream("E:\\temp\\" + Guid.NewGuid().ToString(), FileMode.Create);
			//TextWriter writer = new StreamWriter(fs, new UTF8Encoding());
			//xs.Serialize(writer, esbparam);
			//writer.Close();
			////////////////////////

			ESBTMPPPFSServiceResponse response = service.CallESBTMPPPFSService(esbparam);
		}

		private static ESBHeadInfo GetESBHeader(ECIFSyncStatus sendStatus)
		{
			ESBHeadInfo headinfo = new ESBHeadInfo();
			headinfo.ChannelId = "01";
			headinfo.CompressionFlag = " ";
			headinfo.EncryptionFlag = " ";
			headinfo.LogPayloadFlag = "N";
			headinfo.NeedRequest = " ";
			headinfo.ProcessTimestamp = DateTime.Now.ToString("yyyyMMddhhmmssfff");
			headinfo.RequesterId = "0018";
			headinfo.ServiceId = "00000000000002";
			headinfo.ServiceSn = "100180020" + DateTime.Now.ToString("yyyyMMddhhmmssfff") + (esbHeaderBit ? "01" : "02");
			headinfo.Status = sendStatus == ECIFSyncStatus.Success ? "S" : "F";
			headinfo.SystemId = "0018";
			headinfo.TimeOut = " ";
			headinfo.UserId = " ";
			headinfo.Password = " ";
			headinfo.VersionId = "01";
			esbHeaderBit = !esbHeaderBit;
			return headinfo;
		}


		private List<PFS_Type> GetRelatedPFSs(DCSFileGroup fileGroup, List<PFSMessage> pfsMessageList)
		{
			List<int> ids = fileGroup.Select(d => d.FileId).ToList();
			List<PFSMessage> pfsMessagesRelated = pfsMessageList.Where(p => ids.Contains(p.RefFileId)).ToList();

			PFS_Type pfsTest = new PFS_Type() { };
			pfsTest.Flight = new PFSFlight_Type()
			{
				FlightNumber = fileGroup.FlightNo,
				BoardingAirport = fileGroup.DeptAirport,
				DepartureDate = fileGroup.DeptDate,
				FNPostfix = "",
			};


			List<PFSMessage> group1 = new List<PFSMessage>();

			pfsTest.CountInfoByAirport = group1.Select(message =>
			{


				string[] bpCounts = message.BoardedPassenger.Trim().Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
				string[] padPCounts = message.PadPassenger.Trim().Substring(4).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

				PFSAirportCount_Type PFSAirportCount = new PFSAirportCount_Type();
				PFSAirportCount.DestinationAirport = message.ArrAirport;
				int count = 0;
				PFSAirportCount.BoardedPassenger = bpCounts.Select(c => new PFSCount_Type()
				{
					Count = int.TryParse(c, out count) ? count : 0,
				}).ToArray();
				PFSAirportCount.PADPassenger = padPCounts.Select(c => new PFSCount_Type()
				{
					Count = int.TryParse(c, out count) ? count : 0,
				}).ToArray();
				PFSAirportCount.Infant = new PFSCount_Type() { Count = message.Baby, };
				return PFSAirportCount;

			}).ToArray();
			pfsTest.Configuration = group1.Select(message =>
			{
				PFSCompartment_Type PFSCompartment = new PFSCompartment_Type();
				PFSCompartment.CompartmentIdentifier = "";
				PFSCompartment.CompartmentSeatsNumber = "";
				return PFSCompartment;
			}).ToArray();
			pfsTest.LoadStatusByAirport = group1.Select(message =>
			{
				PFSDestinationAirport_Type PFSDestinationAirport = new PFSDestinationAirport_Type();

				PFSDestinationAirport.CategoryByStatusCode = message.PFSPassengers.GroupBy(p =>
				{
					PFSStatusCode_Type StatusCode = new PFSStatusCode_Type();
					StatusCode.CategoryCode = p.StatusCode;
					StatusCode.ClassIdentifier = p.Class;
					StatusCode.PassengerNumber = p.ClassNum;
					return StatusCode;
				}, new PFSStatusCodeComparer()
				).Select(pg =>
				{
					PFSCategoryByStatusCode_Type PFSCategoryByStatusCode = new PFSCategoryByStatusCode_Type();
					PFSCategoryByStatusCode.StatusCode = pg.Key;
					PFSCategoryByStatusCode.Passenger = pg.Select(p =>
					{
						PFSPassengerInfo_Type PFSPassengerInfo = new PFSPassengerInfo_Type();
						PFSPassengerInfo.FamilyName = p.PName.IndexOf('/') != -1 ? p.PName.Split('/')[0] : "";
						PFSPassengerInfo.GivenName = p.PName.IndexOf('/') != -1 ? p.PName.Split('/')[1] : p.PName;
						PFSPassengerInfo.FullName = p.PName;
						PFSPassengerInfo.FFCardCode = new PFSFFCardInfo_Type()
						{
							AirlineCode = "",
							CardLevel = "",
							FFCardNo = "",
						};
						PFSPassengerInfo.PNR = p.PNR;
						PFSPassengerInfo.PassengerId = new PFSPassengerId_Type()
						{
							FFPIdentification = "",
							FirstNameInitialsTitle = "",
							Surname = "",
						};
						PFSPassengerInfo.PassengerNumberBySurname = "";
						PFSPassengerInfo.PreferredTitle = "";
						return PFSPassengerInfo;
					}).ToArray();
					return PFSCategoryByStatusCode;
				}).ToArray();
				PFSDestinationAirport.DestinationAirport = message.ArrAirport;
				return PFSDestinationAirport;
			}).ToArray();
			pfsTest.SharedFlightIdentifier = group1.First().SharedNo;
			string[] tpCounts = group1.First().TransitPassenger.Trim().Split(new char[] { '\x20' }, StringSplitOptions.RemoveEmptyEntries);
			//pfs.TransitInfo = new PFSTransitInfo_Type()
			//{
			//    TransitInfant = new PFSCount_Type()
			//    {
			//        Count = group1.First().TransitBaby,
			//    },
			//    TransitPassenger = tpCounts.Select(c => new PFSCount_Type
			//    {
			//        Count = int.Parse(c),
			//    }).ToArray(),
			//};
			pfsTest.TransitInfo = null;

			List<PFS_Type> pfsList = new List<PFS_Type>();

			return pfsList;
		}


		private ESBTMPPPFSService1 GetESBParam(DCSFileGroup group, List<PFSMessage> pfsList, bool flightOnly)
		{
			ESBTMPPPFSService1 result = new ESBTMPPPFSService1();
			List<PFS_Type> pfs = GetRelatedPFSs(group, pfsList);

			result.PFSMessage = pfs.ToArray();

			return result;
		}

	}

	public enum ECIFSyncStatus
	{
		Success,

		Failed,
	}

	internal class PFSStatusCodeComparer : IEqualityComparer<PFSStatusCode_Type>
	{
		public bool Equals(PFSStatusCode_Type x, PFSStatusCode_Type y)
		{
			return x.CategoryCode == y.CategoryCode &&
				x.ClassIdentifier == y.ClassIdentifier &&
				x.PassengerNumber == y.PassengerNumber;
		}

		public int GetHashCode(PFSStatusCode_Type obj)
		{
			return 0;
		}
	}

}
